package com.lkj.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author likanjia
 */
public class GroupChatServer1 {

    private Selector selector;

    private ServerSocketChannel ssc;

    public static final int PORT = 6668;

    public GroupChatServer1() {

        try {
            selector = Selector.open();

            ssc = ServerSocketChannel.open();

            ssc.socket().bind(new InetSocketAddress(PORT));

            ssc.configureBlocking(false);

            ssc.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void lisent()  {
        try {
            while (true) {
                int select = selector.select();
                if (select > 0 ){
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();

                        if (key.isAcceptable()) {
                            SelectableChannel channel = key.channel();
                            channel.configureBlocking(true);
                            channel.register(selector,SelectionKey.OP_READ);
                        }

                        if (key.isReadable()) {
                            SocketChannel channel = (SocketChannel) key.channel();

                            ByteBuffer buffer = ByteBuffer.allocate(1024);

                            int read = channel.read(buffer);

                            if (read >0) {
                                String msg = new String(buffer.array());

                                System.out.println(msg);
                            }


                        }

                    }
                }
            }
        } catch (Exception ex) {

        }
    }
}
